<?php
namespace Api\Controller;

use Think\Controller;
class ImageController extends Controller{
	
	private function setBrowserCache( $prefix, $url, $ext ) {
		$offset = 30*60*60*24; // cache 1 month
		$time = cookie("{$prefix}".md5($url));
		$time or cookie(md5($url), $time = time(), "expire=$offset&prefix={$prefix}");
		header("Content-Type:image/{$ext}");
		header("Pragma:cache");
		header("Last-Modified: " . gmdate ("r", $time));
		header("Expires:".gmdate("D, d M Y H:i:s", time() + $offset)." GMT");
		header("Cache-Control:max-age=$offset");
	}
	
	public function showAction() {
		$url = I('url');
		$data = F($url);
		$data or $data = $this->save($url);
		$ext = pathinfo($url, PATHINFO_EXTENSION);
		header("Content-Type:image/{$ext}");
		$this->setBrowserCache('show_', $url, $ext);
		echo $data;
	}
	
	public function thumbAction() {
		$url = I('url');
		$ext = pathinfo($url, PATHINFO_EXTENSION);
		$thumbUrl = $this->getThumbName($url, 'thumb');
		$data = F($thumbUrl);
		$data or $data = $this->save($url, true, 'thumb');
		$this->setBrowserCache('thumb_', $url, $ext);
		echo $data;
	}
	
	public function smallAction() {
		$url = I('url');
		$thumbUrl = $this->getThumbName($url, 'small');
		$data = F($thumbUrl);
		$data or $data = $this->save($url, true, 'small');
		$ext = pathinfo($url, PATHINFO_EXTENSION);
		header("Content-Type:image/{$ext}");
		echo $data;
	}
	
	private function save($url, $thumb=false, $tag = 'thumb') {
		if ($thumb) {
			$THUMB_SIZES = C("THUMB_SIZES.$tag");
			$data = $this->thumb($url, $THUMB_SIZES['width'], $THUMB_SIZES['height']);
			$url = $this->getThumbName($url, $tag);
		} else {
			$data = file_get_contents($url); 
		}
		F($url, $data);
		return $data;
	}
	
	private function getThumbName($url, $tag) {
		return preg_replace('/(\.\w+)$/', "_{$tag}$1", $url);
	}
	
	/**
	 * 
	 * @param unknown $url http://wmei-wmei5.stor.sinaapp.com/2014-08-18/2014081811103082385716.jpg
	 * @param unknown $maxWidth
	 * @param unknown $maxHeight
	 * @return string
	 */
	private function thumb($url, $maxWidth, $maxHeight) {
		$imgInfo = getimagesize(preg_replace('/http:\/\/[^\/]+/', "saestor://wmei5", $url));
		$width = $imgInfo[0];//获取图片宽度
		$height = $imgInfo[1];//获取图片高度
		$r = min($maxHeight/$height, $maxWidth/$width);
		if($r >= 1) {
			$maxHeight = $height;
			$maxWidth = $width;
		} elseif($r < 1) {
			$maxHeight = $height * $r;
			$maxWidth = $width * $r;
		}
		$temp_img = imagecreatetruecolor($maxWidth,$maxHeight); //创建画布
		$fun = str_replace('/', 'createfrom', $imgInfo['mime']);
		$im = $fun($url);
		imagecopyresized($temp_img,$im,0,0,0,0,$maxWidth,$maxHeight,$width,$height);
	
		ob_start();
		$fun = str_replace('/', '', $imgInfo['mime']);
		$fun($temp_img);
		$imgstr = ob_get_contents();
		ob_end_clean();
		imagedestroy($im);
		return $imgstr;
	}
	
	
}